package sopia.sg;

import java.util.ArrayList;

import sopia.cmm.CommonFunct;
import sopia.cmm.Constant;
import sopia.conn.AccountAdapter;
import sopia.conn.CustomerSpinnerAdapter;
import sopia.conn.ExpenseAdapter;
import sopia.conn.ItemExpenseAdapter;
import sopia.ctrl.ItemExpense;
import sopia.ctrl.ItemExpenseCustomizeAdapter;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.database.Cursor;
import android.database.SQLException;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout.LayoutParams;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

public class TabAccountActivity extends ListActivity {
	private AccountAdapter accAdapter ;
	private ExpenseAdapter expAdapter ;
	private ItemExpenseAdapter itemAdapter ;
	private ListView lstAccount;
	private String[] names ;
	
	PopupWindow popUp;
	 LinearLayout layout;
	 TextView tv;
	 LayoutParams params;
	 LinearLayout mainLayout;
	 
	 boolean click = true;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initial();
        
		
	
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	  //Handle the back button
	  if (keyCode == KeyEvent.KEYCODE_BACK) {
		  Intent i = new Intent(TabAccountActivity.this, G001Activity.class);
			i.putExtra("ID", "G002");
			startActivity(i);
			finish();
	    return true;
	  }

	  return super.onKeyDown(keyCode, event);
	} 
	private void initial() {
	    popUp = new PopupWindow(this);
	    layout = new LinearLayout(this);
	    mainLayout = new LinearLayout(this);
	    tv = new TextView(this);
	    
		this.names  = initListAccount();
	    setListAdapter(new ArrayAdapter<String>(this, R.layout.g006_accounts_layout, names));
	    this.lstAccount = getListView();
	    lstAccount.setTextFilterEnabled(true);
	    registerForContextMenu(this.lstAccount);
	}
	private void showDetailsEntry(String accountName){
		try {
			accAdapter = new AccountAdapter(this);
			String tmp = accAdapter.getAmountCurrency(accountName);
			String[] arr = CommonFunct.removeHash(tmp);
			if(arr != null && arr.length > 1){
				String textShow = Constant.EMPTY_STRING;
				textShow += CommonFunct.join("Account name : " , arr[0],"\n","Amount : ", arr[1]);
				 params = new LayoutParams(LayoutParams.WRAP_CONTENT,
				    LayoutParams.WRAP_CONTENT);
				  layout.setOrientation(LinearLayout.VERTICAL);
				  tv.setText(textShow);
				  layout.addView(tv, params);
				  popUp.setContentView(layout);
			}
			accAdapter.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	@Override
	    public void onCreateContextMenu(ContextMenu menu, View v,
	        ContextMenuInfo menuInfo) {
		  if (v.getId()==android.R.id.list) {
			    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
			    menu.setHeaderTitle(names[info.position]);
			    String[] menuItems = getResources().getStringArray(R.array.menu_view);
			    for (int i = 0; i<menuItems.length; i++) {
			      menu.add(Menu.NONE, i, i, menuItems[i]);
			    }
		}
	    }
	  @Override
	    public boolean onContextItemSelected(MenuItem item) {
		  AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
		  int menuItemIndex = item.getItemId();
		  final String accountName = names[info.position];
	      switch( menuItemIndex)
	      {
		      case 0: //delete	    
		    	  	new AlertDialog.Builder(this)
		    	    .setTitle(CommonFunct.join("Delete item ", accountName))
		    	    .setMessage("Are you sure you want to delete this item?")
		    	    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		    	        public void onClick(DialogInterface dialog, int which) { 
		    	            deleteAccount(accountName);
		    	        }
		    	     })
		    	    .setNegativeButton("No", new DialogInterface.OnClickListener() {
		    	        public void onClick(DialogInterface dialog, int which) { 
		    	      		//do nothing
		    	        }
		    	     })
		    	     .show();	    	  
		    	  break;
		      case 1: // show details
		    	    if (click) {
   	      		     popUp.showAtLocation(layout, Gravity.BOTTOM, 10, 10);
   	      		     popUp.update(50, 50, 300, 80);
   	      		     click = false;
   	      		    } else {
   	      		     popUp.dismiss();
   	      		     click = true;
   	      		    }
   	      			showDetailsEntry(accountName);
		    	  break;
		      default:
		    	  
	      }
	    

	      return true;
	    }
	  protected void deleteAccount(String accountName) {
			try {
				accAdapter = new AccountAdapter(this);
				if(accAdapter.deleteAccount(accountName)){
					accAdapter.close();
					Toast.makeText(this,"Removed item selected." , Toast.LENGTH_LONG).show();
					deleteTypeExpenseByAccount(accountName);
					deleteItemExpenseByAccount(accountName);
					initial();   
				}	
			
			} catch (Exception e) {
				e.printStackTrace();
			}
		
	}
	private void deleteItemExpenseByAccount(String accountName) {
		try {
			itemAdapter = new ItemExpenseAdapter(this);
			if(itemAdapter.deleteItemExpenseByAccount(accountName)){
				itemAdapter.close();
				initial();   
			}	
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private void deleteTypeExpenseByAccount(String accountName) {
		try {
			expAdapter = new ExpenseAdapter(this);
			if(expAdapter.deleteExpenseByAccount(accountName)){
				expAdapter.close();
				initial();   
			}	
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private String[] initListAccount() {
		String[] names = null ;
		try {
			accAdapter = new AccountAdapter(this);
			Cursor cur = accAdapter.getAllAccount();
			names = new String[cur.getCount()];
			int i = 0 ;
			if (cur.moveToFirst()) {
			     do {
			    	 names[i++] = cur.getString(0);
			     } while (cur.moveToNext());
			 }
			if (cur != null && !cur.isClosed()) {
				  cur.close();
			}		
			accAdapter.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return names;
	}	
 
}
